package com.example.homeworkmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.homeworkmanagement.pojo.Students;
import com.example.homeworkmanagement.pojo.Teachers;
import com.example.homeworkmanagement.mapper.TeachersMapper;
import com.example.homeworkmanagement.service.TeachersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.homeworkmanagement.vo.ResultVO;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 拒绝加班
 * @since 2025-05-25
 */
@Service
public class TeachersServiceImpl extends ServiceImpl<TeachersMapper, Teachers> implements TeachersService {
    @Override
    public ResultVO<Teachers> login(String teacher_id, String password) throws Exception {
        QueryWrapper<Teachers> qw = new QueryWrapper<>();
        qw.eq("teacher_id", teacher_id);
        // 获取一个
        Teachers teachers = this.getOne(qw);

        if (teachers != null) {
            if (teachers.getPassword().equals(password)) {
                // 返回用户信息和角色信息
                return ResultVO.success("登录成功", teachers);
            } else {
                return ResultVO.fail("密码错误");
            }
        }
        return ResultVO.fail("账号不存在");
    }

    @Override
    public ResultVO<List<Teachers>> getTeacherList(Teachers teacher, int page, int size) {
        QueryWrapper<Teachers> queryWrapper = new QueryWrapper<>();

        // 教师工号（模糊查询）
        if (teacher.getTeacherId() != null && !teacher.getTeacherId().isEmpty()) {
            queryWrapper.like("teacher_id", teacher.getTeacherId());
        }

        // 教师姓名（模糊查询）
        if (teacher.getTeacherName() != null && !teacher.getTeacherName().isEmpty()) {
            queryWrapper.like("teacher_name", teacher.getTeacherName());
        }

        // 性别（精确查询）
        if (teacher.getGender() != null && !teacher.getGender().isEmpty()) {
            queryWrapper.eq("gender", teacher.getGender());
        }

        // 所属院系（模糊查询）
        if (teacher.getDepartment() != null && !teacher.getDepartment().isEmpty()) {
            queryWrapper.like("department", teacher.getDepartment());
        }

        // 联系电话（模糊查询）
        if (teacher.getPhone() != null && !teacher.getPhone().isEmpty()) {
            queryWrapper.like("phone", teacher.getPhone());
        }

        // 电子邮箱（模糊查询）
        if (teacher.getEmail() != null && !teacher.getEmail().isEmpty()) {
            queryWrapper.like("email", teacher.getEmail());
        }

        // 年龄（精确查询）
        if (teacher.getAge() != null) {
            queryWrapper.eq("age", teacher.getAge());
        }

        // 分页查询（page从1开始，size为每页大小）
        Page<Teachers> pageResult = this.page(new Page<>(page, size), queryWrapper);

        List<Teachers> list = this.list(queryWrapper);
        int total= list.size();
        // 返回当前页数据列表
        return ResultVO.success("教师列表获取成功", pageResult.getRecords(),total);
    }
    @Override
    public ResultVO<Teachers> getTeacherDetail(String teacherId) {
        try {
            Teachers teacher = this.getOne(new QueryWrapper<Teachers>().eq("teacher_id", teacherId));
            if (teacher == null) {
                return ResultVO.fail("教师工号不存在");
            }
            return ResultVO.success("教师详情获取成功", teacher);
        } catch (Exception e) {
            return ResultVO.fail("获取教师详情时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Teachers> addTeacher(Teachers teacher) {
        try {
            // 检查工号是否已存在
            if (this.getOne(new QueryWrapper<Teachers>().eq("teacher_id", teacher.getTeacherId())) != null) {
                return ResultVO.fail("该教师工号已存在");
            }

            boolean saveSuccess = this.save(teacher);
            if (!saveSuccess) {
                return ResultVO.fail("教师添加失败");
            }
            return ResultVO.success("教师添加成功", teacher);
        } catch (Exception e) {
            return ResultVO.fail("添加教师时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<Teachers> updateTeacher(Teachers teacher) {
        try {
            // 检查教师是否存在
            Teachers existingTeacher = this.getOne(new QueryWrapper<Teachers>().eq("teacher_id", teacher.getTeacherId()));
            if (existingTeacher == null) {
                return ResultVO.fail("教师工号不存在");
            }

            // 更新字段（只更新非空值且非空字符串）
            String teacherName = teacher.getTeacherName();
            if (teacherName != null && !teacherName.trim().isEmpty()) {
                existingTeacher.setTeacherName(teacherName);
            }

            String password = teacher.getPassword();
            if (password != null && !password.trim().isEmpty()) {
                existingTeacher.setPassword(password);
            }

            String gender = teacher.getGender();
            if (gender != null && !gender.trim().isEmpty()) {
                existingTeacher.setGender(gender);
            }

            String phone = teacher.getPhone();
            if (phone != null && !phone.trim().isEmpty()) {
                existingTeacher.setPhone(phone);
            }

            String email = teacher.getEmail();
            if (email != null && !email.trim().isEmpty()) {
                existingTeacher.setEmail(email);
            }
            String department = teacher.getDepartment();
            if (department != null && !department.trim().isEmpty()) {
                existingTeacher.setDepartment(department);
            }

            Integer age = teacher.getAge();
            if (age != null) { // 整数类型只需判断非null
                existingTeacher.setAge(age);
            }

            boolean updateSuccess = this.updateById(existingTeacher);
            if (!updateSuccess) {
                return ResultVO.fail("教师信息更新失败");
            }
            return ResultVO.success("教师信息更新成功", existingTeacher);
        } catch (Exception e) {
            log.error("更新教师异常", e);
            return ResultVO.fail("更新教师时发生异常：" + e.getMessage());
        }
    }
    @Override
    public ResultVO<Teachers> deleteTeacher(String teacherId) {
        try {
            // 检查教师是否存在
            if (this.getOne(new QueryWrapper<Teachers>().eq("teacher_id", teacherId)) == null) {
                return ResultVO.fail("教师工号不存在");
            }

            boolean deleteSuccess = this.removeById(teacherId);
            if (!deleteSuccess) {
                return ResultVO.fail("教师删除失败");
            }
            return ResultVO.success("教师删除成功");
        } catch (Exception e) {
            log.error("删除教师异常", e);
            return ResultVO.fail("删除教师时发生异常：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<List<String>> selectByTeacherName(String teacherName) {
        if(teacherName==null){
            return ResultVO.fail("教师名称不能为空");
        }
        QueryWrapper<Teachers> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("teacher_name",teacherName);
        List<Teachers> list = this.list(queryWrapper);
        if(list.isEmpty() || list==null){
            return ResultVO.fail("没有查到该教师相关的");
        }
        List<String> list1  = new ArrayList<>();
        for(Teachers teachers:list){
            list1.add(teachers.getTeacherId());
        }
        return ResultVO.success("查询成功",list1);
    }
}
